package com.qys.livesMall.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;


public class MD5Util {

    public static String get(String str){
    //利用try-catch块处理可能出现的异常
		try{
            //根据当前算法,获取加密工具对象(摘要)
            MessageDigest md5 = MessageDigest.getInstance("MD5");

            //更新原始数据,把字符串类型转化成字节
            md5.update(str.getBytes());
            byte[] resultByteArray = md5.digest();

            //加密后的字节数组需要转化成字符串,提前准备一个Stringbuilder
            StringBuilder result = new StringBuilder();

            for (byte bite : resultByteArray) {
                //利用String.format方法设置加密后的字符串格式
                result.append(String.format("%02x", bite));

            }

            //打印输出加密后的字符串
            System.out.println(result);
            return result.toString();

        } catch(NoSuchAlgorithmException e){
            e.printStackTrace();
            return null;
        }
    }

    public static String randomString(int len) {
       String az="abcdefghijklmnopqrstuvwxyz";
        String AB ="abcdefghijklmnopqrstuvwxyz0123456789";
        Random rnd = new Random();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            if (i==0){
                sb.append(az.charAt(rnd.nextInt(az.length())));
                continue;
            }
            sb.append(AB.charAt(rnd.nextInt(AB.length())));
        }
        return sb.toString();
    }

}
